<?php

namespace App\Api\Middleware;


use App\Common\Exception\ApiMessageException;
use App\Common\Util\ApiAuth;
use Sc\Util\Tool\JWT;
use think\Request;
use think\Response;

/**
 * 登录信息认证
 */
class ApiAuthenticateMiddleware
{
    /**
     * @param Request  $request
     * @param \Closure $next
     *
     * @return Response
     * @throws ApiMessageException
     */
    public function handle(Request $request, \Closure $next):Response
    {
        try {
            ApiAuth::verify();
        } catch (ApiMessageException $e) {
            if ($e->getCode() === JWT::EXPIRE_CODE){
                return \App\Common\Util\Response::json()->fail('token refresh',JWT::EXPIRE_CODE);
            }
            throw $e;
        }

        return $next($request);
    }
}